<?php

namespace Biz\module\Classes\adm;

use Biz\model\activity\CouponRecord as mCouponRecord;
use Biz\model\GoodsSku as mGoodsSku;
use Biz\model\ShopBasicInfo as mShopBasicInfo;
use Biz\model\theParagraph\Store as mStore;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderExtend as mOrderExtend;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\trade\OrderRefund as mOrderRefund;
use Biz\module\Classes\OrderGoods as clsOrderGoods;
use Biz\module\Classes\OrderInfo as clsOrderInfo;
use Biz\module\Classes\OrderPackage as clsOrderPackage;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\activity\MealInfo as sMealInfo;
use Biz\service\activity\PinTuan as sPinTuan;
use Biz\service\trade\Order as sOrder;
use Biz\service\trade\ShopCourier as sShopCourier;
use Biz\tools\Amount;
use Biz\tools\OrderNo as toolOrderNo;
use Doraemon\service\User;
use Doraemon\service\User as sUser;
use Doraemon\tools\HhzEnv;
use Biz\model\trade\OrderPackage as mOrderPackage;


class OrderList
{
    public function getInfos($orderNos)
    {
        $orderInfos = mOrder::getOrderInfoList(['order_no' => $orderNos], [], ['addtime' => 'DESC']);
        $orderGoods = mOrderGoods::getFieldsByOrderNo($orderNos);
        $orderRefund = mOrderRefund::getRefundListByOrderNoForMgtDetailAndList($orderNos);
        $orderExtend = mOrderExtend::getOrderListByOrderNos($orderNos);
        $storeList = mStore::getStoreList();
        $stores = [];
        foreach ($storeList as $store) {
            $stores[$store['id']] = $store['abbr'];
        }
        //获取商家昵称
        $shopList = mShopBasicInfo::selectFieldsByFilter([
            'shop_id',
            'name'
        ], ['shop_id' => array_unique(array_column($orderInfos, 'shop_id'))]);
        $shopNames = array_column($shopList, 'name', 'shop_id');
        //获取买家昵称
        $userList = User::getUserInfoByIds(array_unique(array_column($orderInfos, 'uid')));
        $userNames = array_column($userList, 'nick', 'uid');
        $formatData = [];
        foreach ($orderInfos as $orderInfo) {
            $orderInfo['shop_name'] = isset($shopNames[$orderInfo['shop_id']]) ? $shopNames[$orderInfo['shop_id']] : '';
            $orderInfo['user_name'] = isset($userNames[$orderInfo['uid']]) ? $userNames[$orderInfo['uid']]: '';
            $formatData[$orderInfo['order_no']] = $orderInfo;
        }
        foreach ($orderExtend as $extend) {
            $extend['store_name'] = isset($stores[$extend['store_id']]) ? $stores[$extend['store_id']] : "";
            $formatData[$extend['order_no']]['extend'] = $extend;
        }
        foreach ($orderGoods as $goods) {
            $formatData[$goods['order_no']]['goods'][$goods['sku_id']] = $goods;
        }
        foreach ($orderRefund as $orderNo => $refundSku) {
            foreach ($refundSku as $skuId => $refund) {
                $formatData[$orderNo]['goods'][$skuId]['refund'] = $refund;
            }
        }
        //var_dump($formatData);
        return $formatData;
    }


    public function getInfo($orderNo)
    {
        $result = [];

        //判断是否父订单
        if (toolOrderNo::isParentNo($orderNo)) {
            throw new \Exception('父订单号不支持商家查看', 0);
        }

        //获取订单信息
        $orderInfo = mOrder::getOrderInfo($orderNo);

        if (empty($orderNo) || empty($orderInfo)) {
            throw new \Exception('抱歉，该订单不存在', 0);
        }


        //查询order字段
        $fields = [
            'cover_img',
            'title',
            'goods_id',
            'sku_id',
            'sell_price',
            'buy_price',
            'buy_num',
            'discount_amount',
            'pay_amount',
            'promo_type',
            's_coupon_vid',
            's_coupon_amount',
            'sku_desc',
            'refund_order_no',
            'meal_amount',
            'reserve_receipt_time'
        ];

        $orderGoods = mOrderGoods::getFieldsByOrderNo($orderNo, $fields);
        $refundOrderNos = array_filter(array_column($orderGoods, 'refund_order_no'), function ($v) {
            if (empty($v)) {
                return false;
            }
            return true;
        });

        $refundList = mOrderRefund::getRefundOrderList($refundOrderNos, 'adm');
        $shopDomain = HhzEnv::detectShopDomain();

        $skuExpressInfo = @clsOrderGoods::getExpressInfo($orderNo);

        foreach ($orderGoods as &$orderGood) {
            $orderGood['promo_type_desc'] = ActivityInfo::ACTIVITY_TYPES_MAPS[$orderGood['promo_type']];
            $orderGood['goods_h5_url'] = $shopDomain . 'h5_goodsDetail/?goods_id=' . $orderGood['goods_id'];
            if (empty($orderGood['refund_order_no'])) {
                $orderGood['status'] = $orderInfo['status'];
                $orderGood['status_desc'] = mOrder::$statusAdmDesc[$orderInfo['status']];
            } else {
                if (empty($refundList[$orderGood['refund_order_no']]['rights_status'])) {
                    $orderGood['status'] = $refundList[$orderGood['refund_order_no']]['status'];
                    $orderGood['status_desc'] = $refundList[$orderGood['refund_order_no']]['status_desc'];
                    $orderGood['is_rights'] = 0; //退款
                } else {
                    $orderGood['status'] = $refundList[$orderGood['refund_order_no']]['rights_status'];
                    $orderGood['status_desc'] = mOrderRefund::$rightsStatusAdmDesc[$orderGood['status']];
                    $orderGood['is_rights'] = 1; //维权
                }
            }
            $orderGood['cover_img'] = $orderGood['cover_img_thumb_url'];

            $orderGood['express_info'] = isset($skuExpressInfo[$orderGood['sku_id']]) ? $skuExpressInfo[$orderGood['sku_id']] : [];

            $orderGood['reserve_receipt_time'] = strtotime($orderGood['reserve_receipt_time']) > 0 ? $orderGood['reserve_receipt_time'] : '';
        }

        //处理数据返回
        $result['order_no'] = $orderNo;
        $result['nick'] = sUser::getUser($orderInfo['uid'])['nick'];
        $result['uid'] = $orderInfo['uid'];

        //收货人
        $result['accept_info'] = [
            'consignee_address' => str_replace($orderInfo['consignee_info_address'], '', $orderInfo['consignee_address'])
        ];

        //买家留言
        $result['message'] = $orderInfo['message'];


        //店铺优惠券信息
        if ($orderInfo['s_coupon_vid'] > 0) {
            $result['s_coupon_info'] = mCouponRecord::get(['title'], ['coupon_vid' => $orderInfo['s_coupon_vid']]);
        }

        //订单状态
        $result['status'] = $orderInfo['status'];
        $result['status_desc'] = mOrder::$statusAdmDesc[$orderInfo['status']];

        //物流信息
        $result['delivery_tracking'] = clsOrderInfo::getOrderDeliveryTracking($orderNo, $orderInfo);

        //积分抵扣金额
        $result['integral_amount'] = $orderInfo['integral_amount'];

        //优惠券抵扣金额
        $result['coupon_amount'] = $orderInfo['coupon_amount'];

        //店铺优惠券抵扣金额
        $result['s_coupon_amount'] = $orderInfo['s_coupon_amount'];

        //活动补贴
        $result['activity_allowance'] = $orderInfo['activity_allowance'];


        //套餐优惠信息
        $result['meal_id'] = $orderInfo['meal_id'];
        $result['meal_title'] = $orderInfo['meal_id'] ? sMealInfo::getMeal($orderInfo['meal_id'])['meal_title'] : '';
        $result['meal_amount'] = $orderInfo['meal_amount'];

        //订单实际付款
        $result['pay_amount'] = $orderInfo['pay_amount'];

        //运费  订单金额
        $result['shipping_amount'] = $orderInfo['shipping_amount'];
        $result['goods_amount'] = $orderInfo['goods_amount'];
        $result['order_amount'] = Amount::format($result['shipping_amount'] + $result['goods_amount']);

        //商品详情
        $result['goods_info'] = $orderGoods;



        $orderPackage = mOrderPackage::getFirstPackageInfo($orderNo);


        //物流公司
        $result['courier_id'] = sShopCourier::getCourierIdByCourierName($orderPackage['express_company']);


        return $result;
    }

    /**
     * 商家管理后台订单列表
     * @param $list
     * @param $sortType
     * @return array
     */
    public static function sellerOrderList($list, $sortType)
    {
        $goodsList = [];
        $orderNos = $list['rows'];
        $order = [
            1 => ['addtime' => 'DESC'],
            2 => ['addtime' => 'ASC'],
        ];
        $orders = mOrder::select('*', ['AND' => ['order_no' => $orderNos], 'ORDER' => $order[$sortType]]);

        $nowTime = time();

        //发货日期临近提醒
        $shipTip = [];

        if ($orderNos) {
            $orderGoodsList = mOrderGoods::getFieldsByOrderNo($orderNos, '*');

            $skuIds = array_column($orderGoodsList, 'sku_id');

            $skuList = mGoodsSku::getInfoList($skuIds);

            $skuNos = array_column($skuList, 'sku_no', 'id');
            $forcastShipTimes = array_column($skuList, 'forecast_ship_time', 'id');

            $refundList = mOrderRefund::getRefundListByOrderNoForMgtDetailAndList($orderNos);
            $orderRemarks = sOrder::OrderRemarks($orderNos);


            foreach ($orderGoodsList as $key => $orderGoods) {
                $orderGoods['refund_order_no'] = $refundList[$orderGoods['order_no']][$orderGoods['sku_id']]['refund_order_no'];
                $orderGoods['rights_process_method'] = $refundList[$orderGoods['order_no']][$orderGoods['sku_id']]['rights_process_method'];
                $orderGoods['refund_status'] = $refundList[$orderGoods['order_no']][$orderGoods['sku_id']]['status'];
                $orderGoods['refund_status_desc'] = $refundList[$orderGoods['order_no']][$orderGoods['sku_id']]['status_desc'];
                $orderGoods['rights_status'] = $refundList[$orderGoods['order_no']][$orderGoods['sku_id']]['rights_status'];
                $orderGoods['rights_status_desc'] = $refundList[$orderGoods['order_no']][$orderGoods['sku_id']]['rights_status_desc'];
                $orderGoods['type_refund'] = $refundList[$orderGoods['order_no']][$orderGoods['sku_id']]['type_refund'];
                $orderGoods['cover_img'] = $orderGoods['cover_img_thumb_url'];
                $orderGoods['sku_no'] = $skuNos[$orderGoods['sku_id']];
                $orderGoods['forcast_ship_time'] = $forcastShipTimes[$orderGoods['sku_id']];


                //商品预期发货时间有效性检测
                if ($orderGoods['forcast_ship_time'] > '2010-01-01') {
                    $shipTip[$orderGoods['order_no']][] = $orderGoods['forcast_ship_time'];
                }
                $orderGoods['goods_amount'] = $orderGoods['goods_amount'] - $orderGoods['s_coupon_amount'] - $orderGoods['meal_amount'];
                $goodsList[$orderGoods['order_no']][] = $orderGoods;

                //是否参与活动
                if ($orderGoods['promo_type'] > 0) {
                    $activitys[$orderGoods['promo_type']][] = $orderGoods['order_no'];
                }
            }
        }

        if (isset($activitys)) {
            $activity = self::getActivity($activitys, $orderGoodsList);
        }

        $orderPackageList = mOrderPackage::getExpressInfoList($orderNos);


        //var_dump(mOrderGoods::sqlLogs());die;
        foreach ($orders as &$orderInfo) {


            if ($orderInfo['consignee_area']) {
                $orderInfo['consignee_code'] = [
                    $orderInfo['consignee_province'],
                    $orderInfo['consignee_city'],
                    $orderInfo['consignee_area']
                ];
            } else {
                $orderInfo['consignee_code'] = [
                    $orderInfo['consignee_province'],
                    $orderInfo['consignee_city']
                ];
            }


            $orderInfo['courier_id'] = sShopCourier::getCourierIdByCourierName($orderPackageList[$orderInfo['order_no']][0]['express_company']);
            $orderInfo['status_desc'] = mOrder::$statusMgtDesc[$orderInfo['status']];
            $orderInfo['order_amount'] = Amount::format($orderInfo['goods_amount'] + $orderInfo['shipping_amount'] - $orderInfo['s_coupon_amount'] - $orderInfo['meal_amount']);
            $orderInfo['goods'] = $goodsList[$orderInfo['order_no']];

            $orderInfo['ship_tip_msg'] = (function () use ($orderInfo, $shipTip, $nowTime) {
                if (empty($shipTip[$orderInfo['order_no']])) {
                    return '';
                }
                foreach ($shipTip[$orderInfo['order_no']] as $time) {

                    if (empty($orderInfo['consignee_time'])) {
                        continue;
                    }
                    if (!empty($time)) {
                        if (strtotime($orderInfo['consignee_time']) >= strtotime($time) && strtotime($time) <= $nowTime) {
                            return '请及时发货';
                        }
                    } else {
                        if (strtotime($orderInfo['consignee_time']) <= $nowTime) {
                            return '请及时发货';
                        }
                    }
                }
            })();

            $orderInfo['seller_message'] = $orderRemarks[$orderInfo['order_no']]['seller_messages'];
            $orderInfo['hhz_message'] = isset($orderRemarks[$orderInfo['order_no']]) ? $orderRemarks[$orderInfo['order_no']]['hhz_message'] : [];

            $orderInfo['package_list'] = clsOrderPackage::getOrderPackageList($orderInfo['order_no']);


            if (isset($activity) && !empty($activity)) {
                foreach ($activity as $_ak => &$_av) {
                    if (isset($_av[$orderInfo['order_no']])) {
                        $orderInfo[$_ak] = $_av[$orderInfo['order_no']];
                    }
                }
            }
        }

        return [
            'all_count' => $list['aggregations'],
            'count' => $list['total'],
            'list' => $orders,
        ];
    }


    private static function getActivity($activity, $skuList)
    {
        $data = [];
        foreach (ActivityInfo::ACTIVITY_TYPES_MAPS as $_k => $_v) {
            switch ($_k) {
                case ActivityInfo::ACTIVITY_TYPE_PINTUAN;
                    $data = sPinTuan::getSkuOrder($activity[ActivityInfo::ACTIVITY_TYPE_PINTUAN], $skuList);
                    break;
            }
        }
        return $data;
    }
}
